import threading
import time
import pynput.keyboard as pk

keyboard_value = ''
dome_code = ''


def set_run_dome_code(param_value):
    global dome_code
    dome_code = param_value
    threading.Thread(target=is_dome_code_thread).start()


def get_run_dome_code():
    global dome_code
    return dome_code


def set_keyboard_value(param_value):
    global keyboard_value
    keyboard_value = param_value


def get_keyboard_value():
    global keyboard_value
    return keyboard_value


def on_press(key):
    # 监听按键
    key = str(key)
    if key == 'Key.esc':
        set_keyboard_value(key)


def keyboard_listen():
    # 连接事件以及释放
    with pk.Listener(on_press=on_press) as pklistener:
        pklistener.join()


def is_dome_code_thread():
    codes = get_run_dome_code()
    if codes != '':
        try:
            exec(codes)
            set_run_dome_code("")
        except Exception as e:
            print(e)
    time.sleep(2)
